package cms.simmytech.dialect;

import cms.simmytech.service.UserService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;
import org.thymeleaf.IEngineConfiguration;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.model.IModel;
import org.thymeleaf.model.IModelFactory;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractElementTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.standard.expression.IStandardExpression;
import org.thymeleaf.standard.expression.IStandardExpressionParser;
import org.thymeleaf.standard.expression.StandardExpressions;
import org.thymeleaf.templatemode.TemplateMode;

import cms.simmytech.model.SysPermission;

public class PermissionNameCustomDialect extends AbstractElementTagProcessor {

	Log log = LogFactory.getLog(RoleCustomDialect.class);

	private UserService userService;

	private static final String TAG_NAME = "permission";
	private static final int PRECEDENCE = 1000;

	public PermissionNameCustomDialect(final String dialectPrefix, UserService userService) {
		super(TemplateMode.HTML, // 此处理器将仅应用于HTML模式
				dialectPrefix, // 要应用于名称的匹配前缀
				TAG_NAME, // 标签名称：匹配此名称的特定标签
				true, // 没有应用于标签名的前缀
				null, // 无属性名称：将通过标签名称匹配
				false, // 没有要应用于属性名称的前缀
				PRECEDENCE// 优先(内部方言自己的优先
		);
		this.userService = userService;
	}

	@Override
	protected void doProcess(ITemplateContext context, IProcessableElementTag tag,
			IElementTagStructureHandler structureHandler) {
		String pIdStr = tag.getAttributeValue("pId");
		if (!StringUtils.isEmpty(pIdStr)) {
			pIdStr = getExpressionValue(context, pIdStr).toString();
			SysPermission permission = userService.getPermission(Integer.parseInt(pIdStr));
			if (null != permission) {
				IModelFactory modelFactory = context.getModelFactory();
				IModel model = modelFactory.createModel();
				model.add(modelFactory.createText(permission.getDescritpion()));
				structureHandler.replaceWith(model, false);
			}
		}
	}

	private Object getExpressionValue(ITemplateContext iTemplateContext, String expressionString) {
		final IEngineConfiguration configuration = iTemplateContext.getConfiguration();
		final IStandardExpressionParser parser = StandardExpressions.getExpressionParser(configuration);
		// 解析expression
		final IStandardExpression expression = parser.parseExpression(iTemplateContext, expressionString);
		// 获取expression的执行结果
		return expression.execute(iTemplateContext);
	}
}
